package com.ts.file.controller;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.ts.common.core.utils.Result;
import com.ts.common.security.dto.UserLoginDto;
import com.ts.feign.dto.UserDTO;
import com.ts.feign.user.UserFeign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController()
@RequestMapping("/file")
@Slf4j
public class FileController {


//    @Autowired
//    private UserFeign userFeign;
    //待完善
    // @Autowired
    // private UserFeign userFeign;


    @Value("${ts.ak}")
    private String ak;

    @Value("${ts.sk}")
    private String sk;

    @Value("${ts.bucket}")
    private String bucket;

    @Autowired
    private UploadManager uploadManager;

    @Value("${ts.host}")
    private String host;

    @PostMapping("/upload")
    public Result upload(MultipartFile file){

        String originalFilename = file.getOriginalFilename();

        String key = "weixin/"+originalFilename;
//        String key  ="";
        //1.通过七牛云ak和sk这个token上传
        Auth auth = Auth.create(ak, sk);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            //2、解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);

            //3、上传成功后调用修改的头像的方法
//            UserDTO userDTO=new UserDTO();
//            userDTO.setAvatar(host+key);
//            System.out.println("用户的头像："+userDTO.getAvatar());
//            userDTO.setId(userLoginDto.getUserId());
//            System.out.println("userDto----》"+userDTO);
//            userFeign.currentUserInfo(userDTO);
        } catch (QiniuException ex) {
            ex.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        log.debug(host+key);
        return new Result().Viewok(host+key);
    }
}
